/**
 * 智能体详情页面组件
 *
 * 功能特性：
 * - 智能体详细信息展示
 * - 智能体状态管理
 * - 操作历史记录
 * - 测试功能
 * - 统计信息展示
 *
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect } from 'react';
import {
  Card,
  Descriptions,
  Tag,
  Button,
  Space,
  message,
  Tabs,
  Spin,
  Alert,
  Statistic,
  Row,
  Col,
  Badge,
  Modal,
  Form,
  Input
} from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import {
  ArrowLeftOutlined,
  EditOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  DeleteOutlined,
  ReloadOutlined,
  BarChartOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SettingOutlined
} from '@ant-design/icons';
import agentService, { AgentStatus, AgentDto } from '@services/agentService';

const { TextArea } = Input;

interface TestResult {
  success: boolean;
  response: string;
  executionTime: number;
  timestamp: string;
}

const AgentDetail: React.FC = () => {
  const [agent, setAgent] = useState<AgentDto | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [testModalVisible, setTestModalVisible] = useState(false);
  const [testInput, setTestInput] = useState('');
  const [testResult, setTestResult] = useState<TestResult | null>(null);
  const [testLoading, setTestLoading] = useState(false);
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();

  useEffect(() => {
    if (id) {
      loadAgent();
    }
  }, [id]);

  const loadAgent = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      setError(null);
      const response = await agentService.getAgent(id);
      setAgent(response);
    } catch (err) {
      setError('加载智能体详情失败');
      console.error('Agent detail loading error:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleStart = async () => {
    if (!id) return;
    
    try {
      await agentService.startAgent(id);
      message.success('启动成功');
      loadAgent();
    } catch (error) {
      message.error('启动失败');
    }
  };

  const handleStop = async () => {
    if (!id) return;
    
    try {
      await agentService.stopAgent(id);
      message.success('停止成功');
      loadAgent();
    } catch (error) {
      message.error('停止失败');
    }
  };

  const handleDelete = async () => {
    if (!id) return;
    
    try {
      await agentService.deleteAgent(id);
      message.success('删除成功');
      navigate('/agents');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const getStatusInfo = (status: AgentStatus) => {
    switch (status) {
      case AgentStatus.NotConfigured:
        return { text: '未配置', color: 'default', icon: <SettingOutlined /> };
      case AgentStatus.Configured:
        return { text: '已配置', color: 'processing', icon: <CheckCircleOutlined /> };
      case AgentStatus.Running:
        return { text: '运行中', color: 'success', icon: <PlayCircleOutlined /> };
      case AgentStatus.Stopped:
        return { text: '已停止', color: 'warning', icon: <PauseCircleOutlined /> };
      case AgentStatus.Error:
        return { text: '错误', color: 'error', icon: <CloseCircleOutlined /> };
      default:
        return { text: '未知', color: 'default', icon: <SettingOutlined /> };
    }
  };

  const handleTest = async () => {
    if (!id || !testInput.trim()) return;

    setTestLoading(true);
    try {
      const result = await agentService.testAgent(id, { input: testInput });
      setTestResult({
        success: true,
        response: result.response || '测试成功',
        executionTime: result.executionTime || 0,
        timestamp: new Date().toISOString()
      });
      message.success('测试执行成功');
    } catch (error) {
      setTestResult({
        success: false,
        response: '测试执行失败',
        executionTime: 0,
        timestamp: new Date().toISOString()
      });
      message.error('测试执行失败');
    } finally {
      setTestLoading(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (error || !agent) {
    return (
      <Alert
        message="错误"
        description={error || '智能体不存在'}
        type="error"
        showIcon
        style={{ marginBottom: 24 }}
      />
    );
  }

  const statusInfo = getStatusInfo(agent.status);

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        {/* 页面标题和操作栏 */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Space>
              <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/agents')}>
                返回列表
              </Button>
              <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold' }}>
                智能体详情
              </h1>
            </Space>
            <Space>
              <Button
                icon={<EditOutlined />}
                onClick={() => navigate(`/agents/${agent.id}/edit`)}
              >
                编辑
              </Button>

              {agent.status === AgentStatus.Running ? (
                <Button
                  icon={<PauseCircleOutlined />}
                  onClick={handleStop}
                  danger
                >
                  停止
                </Button>
              ) : (
                <Button
                  icon={<PlayCircleOutlined />}
                  onClick={handleStart}
                  type="primary"
                  disabled={agent.status === AgentStatus.NotConfigured}
                >
                  启动
                </Button>
              )}

              <Button
                icon={<BarChartOutlined />}
                onClick={() => setTestModalVisible(true)}
              >
                测试
              </Button>
            </Space>
          </div>
        </div>

        {/* 基本信息 */}
        <Card title="基本信息" style={{ marginBottom: '24px' }}>
          <Descriptions bordered column={2}>
            <Descriptions.Item label="名称" span={2}>
              {agent.name}
            </Descriptions.Item>
            <Descriptions.Item label="状态" span={1}>
              <Badge
                status={statusInfo.color as any}
                text={statusInfo.text}
              />
            </Descriptions.Item>
            <Descriptions.Item label="类型" span={1}>
              <Tag color="blue">
                {agent.agentType === 0 ? '聊天助手' :
                 agent.agentType === 1 ? '智能助手' :
                 agent.agentType === 2 ? '数据分析' :
                 agent.agentType === 3 ? '创意生成' : '自定义'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="描述" span={2}>
              {agent.description}
            </Descriptions.Item>
            <Descriptions.Item label="模型配置" span={1}>
              {agent.modelConfigName || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="提示词模板" span={1}>
              {agent.promptTemplateName || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="激活状态" span={1}>
              <Tag color={agent.isActive ? 'success' : 'default'}>
                {agent.isActive ? '激活' : '停用'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间" span={1}>
              {new Date(agent.createdAt).toLocaleString()}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 配置信息 */}
        <Card title="配置参数" style={{ marginBottom: '24px' }}>
          <Descriptions bordered column={3}>
            <Descriptions.Item label="最大Token数">
              {agent.maxTokens}
            </Descriptions.Item>
            <Descriptions.Item label="温度参数">
              {agent.temperature}
            </Descriptions.Item>
            <Descriptions.Item label="超时时间">
              {agent.timeoutSeconds}秒
            </Descriptions.Item>
            <Descriptions.Item label="标签" span={3}>
              {agent.tags || '-'}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 统计信息 */}
        <Card title="统计信息" style={{ marginBottom: '24px' }}>
          <Row gutter={16}>
            <Col span={6}>
              <Statistic title="使用次数" value={agent.usageCount} />
            </Col>
            <Col span={6}>
              <Statistic title="成功次数" value={agent.successCount} />
            </Col>
            <Col span={6}>
              <Statistic title="失败次数" value={agent.failureCount} />
            </Col>
            <Col span={6}>
              <Statistic
                title="平均响应时间"
                value={agent.averageResponseTimeMs}
                suffix="ms"
              />
            </Col>
          </Row>
        </Card>

        {/* 系统提示词 */}
        <Card title="系统提示词" style={{ marginBottom: '24px' }}>
          <TextArea
            value={agent.systemPrompt}
            rows={8}
            readOnly
            style={{ resize: 'none' }}
          />
        </Card>

        {/* 详细标签页 */}
        <Card>
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: '1',
                label: '配置详情',
                children: (
                  <TextArea
                    value={agent.configuration || '{}'}
                    rows={10}
                    readOnly
                    style={{ resize: 'none', fontFamily: 'monospace' }}
                  />
                )
              }
            ]}
          />
        </Card>
      </Card>

      {/* 测试模态框 */}
      <Modal
        title="测试智能体"
        open={testModalVisible}
        onCancel={() => {
          setTestModalVisible(false);
          setTestInput('');
          setTestResult(null);
        }}
        footer={null}
        width={800}
      >
        <Form layout="vertical">
          <Form.Item label="测试输入">
            <TextArea
              value={testInput}
              onChange={(e) => setTestInput(e.target.value)}
              rows={4}
              placeholder="请输入测试内容..."
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                onClick={handleTest}
                loading={testLoading}
                disabled={!testInput.trim()}
              >
                执行测试
              </Button>
              <Button onClick={() => setTestModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {testResult && (
          <Card
            title="测试结果"
            size="small"
            style={{ marginTop: '16px' }}
          >
            <Descriptions column={1}>
              <Descriptions.Item label="状态">
                <Badge
                  status={testResult.success ? 'success' : 'error'}
                  text={testResult.success ? '成功' : '失败'}
                />
              </Descriptions.Item>
              <Descriptions.Item label="执行时间">
                {testResult.executionTime}ms
              </Descriptions.Item>
              <Descriptions.Item label="响应内容">
                <TextArea
                  value={testResult.response}
                  rows={6}
                  readOnly
                  style={{ resize: 'none' }}
                />
              </Descriptions.Item>
            </Descriptions>
          </Card>
        )}
      </Modal>
    </div>
  );
};

export default AgentDetail;